<template>
  <div class="test-details">
    <basic-container>
      <div class="test-container" v-if="project">
        <p class="test-title">{{ project.projectName }}</p>
        <div class="surveydescription" v-html="project.accessRemark">
          <!-- {{ project.accessRemark }} -->
        </div>

        <div class="question-wrapper">
          <div
            class="question"
            v-for="item of topicList"
            :key="item.sourceSubjectId"
          >
            <p class="question-title require"><i>*</i> {{ item.subjecName }}</p>

            <div class="options-wrapper">
              <el-radio-group
                v-model="item.value"
                v-if="item.type === 1 || item.type === -1"
              >
                <el-radio
                  :label="option.subjectAnswerNo"
                  v-for="option of item.adds"
                  :key="option.subjectAnswerNo"
                >
                  {{ option.answer }}
                </el-radio>
              </el-radio-group>

              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入内容"
                v-model="item.value"
                v-if="item.type === 2"
              >
              </el-input>
            </div>
          </div>

          <!-- <div class="question">
            <p class="question-title require">
              <i>*</i> 2、您对公司目前还有哪些建议和意见：
            </p>

            <div class="options-wrapper">
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入内容"
                v-model="textarea"
              >
              </el-input>
            </div>
          </div> -->
        </div>
        <el-alert title="请填完所有选项" v-show="!isCompleted" type="warning">
        </el-alert>
        <el-button
          type="danger"
          class="submit-btn"
          @click="submit"
          :disabled="!isCompleted"
          :loading="loading"
        >
          提交问卷
        </el-button>

        <!-- <div class="progress-bar">
          <el-progress class="progress" :percentage="50"></el-progress>
          <span>进度</span>
        </div> -->
      </div>
    </basic-container>
  </div>
</template>

<script>
import { getProjectInfo } from "@/api/census";
import { geMeasureList } from "@/api/test";
import dayjs from "dayjs";
import request from "@/router/axios";
import { isUndefined } from "lodash-es";
import { mapMutations } from "vuex";

/**
 * 参考页面 https://www.wjx.cn/jq/17141631.aspx
 */
export default {
  name: "TestDetails",
  props: {
    projectGaugeTypeId: {
      type: String,
      default: "000000_1624704128101_35ee354532e943bca34036623cd259fd",
    },
    projectId: {
      type: String,
      default: "000000_1624707980045_463f3be0304847099bb699d2446d721c",
    },
  },
  computed: {
    duration() {
      const { endTime, startTime } = this;
      return endTime.diff(startTime.value, "m");
    },
    isCompleted() {
      const { topicList } = this;
      return topicList.every(
        (item) => !isUndefined(item.value) && item.value !== ""
      );
    },
  },
  data() {
    return {
      radio: "",
      textarea: "",
      topicList: [],
      project: null,
      startTime: dayjs(),
      endTime: dayjs(),
      loading: false,
      path: "/test/details?",
    };
  },
  created() {
    console.log(this.$route);
  },
  watch: {
    projectId: {
      async handler() {
        if (!this.projectId) {
          return;
        }
        await Promise.all([this.getProjectInfo(), this.geMeasureList()]);
      },
      immediate: true,
    },
  },
  methods: {
    ...mapMutations(["ASSESS_SUBMIT"]),
    async getProjectInfo() {
      if (!this.projectId) return;

      const {
        data: { data },
      } = await getProjectInfo(1, 100, {
        projectId: this.projectId,
      });
      this.topicList = data;
    },
    async geMeasureList() {
      if (!this.projectId) return;

      const {
        data: {
          data: { records },
        },
      } = await geMeasureList(1, 100, {
        projectId: this.projectId,
      });
      this.project = records[0];
    },
    getTime() {
      this.endTime = dayjs();
    },
    async submit() {
      await this.$confirm("是否提交结果?", "恭喜你,完成所有问题", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      });

      const url =
        "/api/blade-measure/measure/userprojectgaugesubjectanswer/submit";
      //加载中效果
      const loading = this.$loading({
        lock: true,
        text: "登录中,请稍后。。。",
        background: "rgba(0, 0, 0, 0.8)",
        spinner: "el-icon-loading",
      });

      this.getTime();
      const datas = this.topicList.map((gauge) => {
        const item = gauge.adds.find(
          ({ subjectAnswerNo }) => subjectAnswerNo === gauge.value
        );
        return formatItem(item, gauge, this.projectId);
      });
      const { startTime, endTime, duration } = this;
      const { gradeId, classNo, sexName, tenantName, account } =
        this.$store.state.user.userInfo;
      const userProjectGaugeEntity = {
        projectId: this.projectId,
        startTime: startTime.format("YYYY-MM-DD HH:mm:ss"),
        endTime: endTime.format("YYYY-MM-DD HH:mm:ss"),
        duration: duration,
        gradeId,
        classNo,
        sex: sexName,
        schoolName: tenantName,
        userName: account,
        // "projectName": "xxx",
      };
      //隐藏加载中效果
      loading.close();

      this.$message.success("恭喜您已完成提交！");
      try {
        this.loading = true;
        const { data } = await request.post(url, {
          datas,
          userProjectGaugeEntity,
        });
        this.$router.push({ name: "首页" });
        window.close();
      } catch (error) {
        console.error(error);
      } finally {
        this.loading = false;
      }
      let data =
        this.path +
        "projectGaugeTypeId=" +
        this.projectGaugeTypeId +
        "&projectId=" +
        this.projectId;
      this.ASSESS_SUBMIT(data);
    },
  },
  mounted() {
    this.startTime = dayjs();
  },
};

function formatItem(item, gauge, projectId) {
  const {
    subjectAnswerNo,
    status,
    sourceSubjectAnswerId,
    score,
    answer,
    projectGaugeSubjectAnswerId,
  } = item;

  const {
    adds,
    projectGaugeId,
    projectGaugeSubjectId,
    // projectId,
    sourceProjectId,
    sourceSubjectId,
    subjecName,
    subjectNo,
    subjectType,
    tenantId,
    fixedType,
  } = gauge;

  const allAnswer = adds.map(({ answer }) => answer).join("|");

  const obj = {
    selectAnswer: answer,
    selectScore: score,
    sourceProjectId,
    gaugeId: sourceProjectId,
    sourceSubjectAnswerId,
    sourceSubjectId,
    subject: subjecName,
    subjectNo,
    subjectType,
    tenantId,
    // userId,
    userProjectGaugeId: projectGaugeId,
    score,
    projectId,
    projectGaugeSubjectId,
    projectGaugeId,
    answer,
    fixedType,
    allAnswer,
  };

  return obj;
}
</script>

<style lang="scss" scoped>
.test-details {
  box-sizing: border-box;
  ::v-deep .basic-container {
    .el-card {
      background: url("./images/background.jpg");
      background-size: cover;
    }
    .el-card__body {
      padding: 42px 0 142px 0;
    }

    .test-container {
      background: white;
      width: 920px;
      // width: 796px;
      margin: 0 auto;
      padding: 20px 30px;
      position: relative;
    }
    .test-title {
      color: #f5495d;
      font-size: 24px;
      font-weight: bold;
      text-align: center;
    }
    .surveydescription {
      color: #555555;
      line-height: 24px;
      text-align: left;
      font-size: 16px;
      padding-bottom: 15px;
      border-bottom: 1px dashed #ccc;
      margin-left: 0;
      margin-top: 20px;
      text-indent: 36px;
    }
  }
  .submit-btn {
    margin: 30px auto;
    display: block;
  }

  .question {
    margin-bottom: 40px;
  }

  .question-title {
    font-size: 15px;
    color: #444444;
    font-weight: bold;
    i {
      visibility: hidden;
      color: red;
      font-weight: bold;
    }
    &.require {
      i {
        visibility: visible;
      }
    }
  }

  .options-wrapper {
    padding-left: 12px;
  }

  .progress-bar {
    text-align: center;
    position: absolute;
    width: 42px;
    border-radius: 2px;
    right: -52px;
    top: 285.5px;
    background: rgb(255, 255, 255);
    height: 150px;
    span {
      line-height: 24px;
      color: #8c8c8c;
      font-size: 12px;
      position: absolute;
      bottom: 0;
      width: 40px;
      left: 1px;
    }
  }

  .progress {
    transform: rotate(90deg) translateY(-30px);
    transform-origin: 0 0;
    width: 130px;
  }
}
</style>
